package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        //自由添加的属性类型为基本属性才添加到属性分组的中间表中
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Integer catelogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", "sale".equals(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        //判断是否是查询所有
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        //获取查询条件
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            //条件不为空,通过属性id或属性名称进行查询
            queryWrapper.and(wrapper -> wrapper.eq("attr_id", key).or().like("attr_name", key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        //获取查询的attr对象,改成响应给页面的attrRespVo
        List<AttrRespVo> attrRespVoList = page.getRecords().stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            Long catelogId1 = attrEntity.getCatelogId();
            //通过attr的分类id查询分类信息
            CategoryEntity categoryEntity = categoryDao.selectById(catelogId1);
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            //通过attr的attr_id查询attrGroup信息
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("attr_id", attrEntity.getAttrId());
            List<AttrAttrgroupRelationEntity> list = relationDao.selectList(wrapper);
            //用来保存attrGroupName的
            StringBuilder attrGroupName = new StringBuilder();
            //对查询出来的attr和attrGroup中间表进行判断非null
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(list.get(i).getAttrGroupId());
                    if (attrGroupEntity != null) {
                        if (i != list.size() - 1) {
                            attrGroupName.append(attrGroupEntity.getAttrGroupName()).append("/");
                        } else {
                            attrGroupName.append(attrGroupEntity.getAttrGroupName());
                        }
                    }
                }
            }
            attrRespVo.setGroupName(attrGroupName.toString());

            return attrRespVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrRespVoList);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //属性类型为基本属性，查询属性分组和中见表的信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            if (attrEntity.getAttrId() != null) {
                QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("attr_id", attrEntity.getAttrId());
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(queryWrapper);
                if (relationEntity!=null){
                    attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
        }
        //查询分类信息
        if (attrEntity.getCatelogId() != null) {
            Long[] cateLogPath = categoryService.findCateLogPath(attrEntity.getCatelogId());
            attrRespVo.setCatelogPath(cateLogPath);
        }
        return attrRespVo;
    }

    @Override
    public void SaveOrUpdateAttr(AttrRespVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        //属性类型为基本属性，查询属性分组和中见表的信息进行更新操作
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //通过属性表的attr_id查询属性和分组的中间表
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id", attr.getAttrId());
            AttrAttrgroupRelationEntity entity = relationDao.selectOne(queryWrapper);

            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            //判断查询处理的属性和分组的中间表是否为空，不为空进行更新操作，为空进行添加操作
            if (entity != null) {

                UpdateWrapper<AttrAttrgroupRelationEntity> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("attr_id", attr.getAttrGroupId());
                relationDao.update(relationEntity, updateWrapper);
            } else {
                relationDao.insert(relationEntity);
            }
        }

    }

    @Override
    public List<AttrEntity> attrRelation(Long attrgroupId) {
        QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id", attrgroupId);
        List<AttrAttrgroupRelationEntity> entityList = relationDao.selectList(queryWrapper);
        List<Long> list = entityList.stream().map(entity ->
                entity.getAttrId()
        ).collect(Collectors.toList());
        List<AttrEntity> attrEntities = this.listByIds(list);

        return attrEntities;
    }

    /**
     * 获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
     *
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils noAttrRelation(Long attrgroupId, Map<String, Object> params) {
        //通过attrgroupId查询分组信息,并获取分类id
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //通过分类id查询还没有关联到本分类下的分组集合
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("catelog_id", catelogId);
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(queryWrapper);
        List<Long> longList = null;
        if (attrGroupEntities != null && attrGroupEntities.size() > 0) {

            //获取没有关联到本分类下的所有分组的id
            longList = attrGroupEntities.stream().map(attrGroupEntity1 -> attrGroupEntity1.getAttrGroupId()).collect(Collectors.toList());
        }
        QueryWrapper<AttrAttrgroupRelationEntity> relationWrapper = new QueryWrapper<>();
        relationWrapper.eq("attr_group_id", longList);
        List<AttrAttrgroupRelationEntity> relationEntityList = relationDao.selectList(relationWrapper);

        List<Long> attrList = relationEntityList.stream().map(relationEntity -> relationEntity.getAttrId()).collect(Collectors.toList());
        //再通过分组id查询到基本信息
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(qw -> qw.eq("attr_id", key).or().eq("attr_name", key));
        }
        if (attrList != null && attrList.size() > 0) {
            wrapper.in("attr_id", attrList);
        }
        wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).eq("catelog_id", catelogId);
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);

    }

    @Override
    public List<Long> getSearchAttrIdS(List<Long> attrIds) {
        List<Long> attrIdS = attrDao.getSearchAttrIdS(attrIds);
        return attrIdS;
    }

}